from config import MOVIES_FOLDER
import os

def get_base_directory():
    """获取基础安全目录的绝对路径"""
    return os.path.abspath(MOVIES_FOLDER)

def resolve_full_path(sub_path):
    """解析完整路径（带规范化处理）"""
    base_dir = get_base_directory()
    return os.path.abspath(os.path.join(base_dir, sub_path))

def validate_path_safety(full_path):
    """验证目标路径是否在安全范围内"""
    base_dir = get_base_directory()
    try:
        # 处理Windows大小写不敏感的情况
        common = os.path.commonpath([base_dir, full_path])
        return os.path.normcase(common) == os.path.normcase(base_dir)
    except ValueError:
        return False

def is_safe_path(sub_path):
    """整合验证流程的主函数"""
    full_path = resolve_full_path(sub_path)
    if validate_path_safety(full_path):
        return True, full_path
    return False, '不是哥们，你在玩目录穿越吗？'


if __name__ == "__main__":
    # 获取真实存在的测试数据
    real_movies_dir = get_base_directory()
    real_folders = [f for f in os.listdir(real_movies_dir) if os.path.isdir(os.path.join(real_movies_dir, f))]
    real_videos = [f for f in os.listdir(real_movies_dir) if f.lower().endswith(('.mp4', '.avi', '.mkv', '.mov'))]

    # 测试基础目录获取
    print(f"[测试1] 基础目录: {get_base_directory()}")
    print(f"实际存在的文件夹: {real_folders[:3]}...（共{len(real_folders)}个）")
    print(f"根目录视频文件: {real_videos[:3]}...（共{len(real_videos)}个）")

    # 生成动态测试用例
    dynamic_test_cases = [
        (real_folders[0], True) if real_folders else ("示例文件夹", True),
        ("../config", False),
        (real_videos[0], True) if real_videos else ("demo.mp4", True),
        ("../../etc/passwd", False),
        ("", True)
    ]

    # 测试主函数
    print("\n[动态测试] 真实环境测试:")
    for path, expected in dynamic_test_cases:
        is_safe, result = is_safe_path(path)
        status = "通过" if is_safe == expected else "失败"
        print(f"测试 {path:<20} => {status} | 安全: {is_safe} | 返回: {result}")
    
    # 测试路径解析
    test_paths = [
        "movies", 
        "../敏感目录", 
        "movies/gtx",
        ""  # 空路径
    ]
    for path in test_paths:
        full = resolve_full_path(path)
        print(f"[测试2] 输入路径: {path:<15} => 解析结果: {full}")

    # 测试路径安全验证
    safe_cases = [
        resolve_full_path(""),          # 根目录
        resolve_full_path("动画电影"),   # 合法子目录
        "e:\\Code\\dgut-video\\movies\\动作电影".upper()  # 测试大小写
    ]
    unsafe_cases = [
        "e:\\Windows\\System32",       # 完全无关路径
        resolve_full_path(".."),        # 上级目录
        resolve_full_path("movies/../../config")  # 嵌套穿越
    ]
    
    print("\n[测试3] 安全路径验证:")
    for path in safe_cases:
        print(f"路径: {path:<45} => 安全: {validate_path_safety(path)}")
    
    print("\n[测试4] 危险路径验证:")
    for path in unsafe_cases:
        print(f"路径: {path:<45} => 安全: {validate_path_safety(path)}")

    # 测试主函数
    print("\n[测试5] 综合测试:")
    test_cases = [
        ("动作电影", True),
        ("../../etc/passwd", False),
        ("纪录片/..", False),
        ("", True)
    ]
    for path, expected in test_cases:
        is_safe, result = is_safe_path(path)
        print(f"输入: {path:<15} => 安全: {is_safe} | 返回: {result}")